<!--
 * @Author: WangShuai 1830773767@qq.com
 * @Date: 2025-06-12 22:47:17
 * @LastEditors: WangShuai 1830773767@qq.com
 * @LastEditTime: 2025-06-17 23:46:38
 * @FilePath: \vue3_admin_template\project\src\components\PublicMap\Maptool.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- 实时路况 -->
  <el-menu-item index="1">
    <template #title>工具箱</template>
  </el-menu-item>
  <div class="mapTool">
    <el-select
      v-model="drawType"
      placeholder="请选择画笔类型"
      @change="activeDraw"
    >
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.label"
        :value="item.value"
      ></el-option>
    </el-select>
    <el-button :plain="true" @click="cancelDraw">清除画笔</el-button>
  </div>
</template>

<script setup lang="ts">
import * as turf from '@turf/turf'
import { ref, onMounted, onUnmounted } from 'vue'
import { mapboxPopup } from '@/utils/mapbox/popup.js'
import useMapStore from '@/store/modules/map'
import setCanvas from '@/utils/mapbox/setCanvas.js'
import type { Feature, FeatureCollection } from './type/type'

let options = [
  {
    id: '00001',
    label: '点',
    value: 'draw_point',
  },
  {
    id: '00002',
    label: '线',
    value: 'draw_line_string',
  },
  {
    id: '00003',
    label: '面',
    value: 'draw_polygon',
  },
  {
    id: '00004',
    label: '矩形',
    value: 'draw_rectangle',
  },
]
let feature = ref()
//新建高亮数据源
let heigh_data: FeatureCollection = {
  type: 'FeatureCollection',
  features: [],
}

let drawType = ref('')
let map: any
let draw: any = null
let isDrawing = ref(false)
//获取数据
const getData = async () => {
  const response = await fetch('/public/aggregation/query.json')
  const result = await response.json()
  feature.value = result
}
//渲染图层
const renderLayer = async () => {
  //添加数据源
  map.addSource('point-source', {
    type: 'geojson',
    data: feature.value,
  })
  //添加点要素图层
  map.addLayer({
    id: 'point-layer',
    source: 'point-source',
    type: 'circle',
    paint: {
      'circle-color': '#409EFF',
      'circle-radius': 20,
    },
  })
  //添加高亮数据源
  map.addSource('heigh-source', {
    type: 'geojson',
    data: heigh_data,
  })
  map.addImage('icon-style', setCanvas({ map }))
  //添加高亮图层
  map.addLayer({
    id: 'heigh-layer',
    source: 'heigh-source',
    type: 'symbol',
    layout: {
      'icon-image': 'icon-style',
      'icon-size': 1,
    },
  })
}
//渲染高亮数据图层
const handleHeightLayer = (data: any) => {
  heigh_data.features = []
  console.log('object', data.features[0])
  let polygon = data.features[0]
  //查询数据源中的要素
  let features = map.querySourceFeatures('point-source')
  if (features) {
    console.log(features)
    features.forEach((feature: Feature) => {
      if (turf.booleanContains(polygon, feature)) {
        heigh_data.features.push(feature)
        map.getSource('heigh-source').setData(heigh_data)
      }
    })
    // //清空画笔图层
    // draw.deleteAll()
  }
}
// 取消绘图
const cancelDraw = () => {
  if (draw) {
    draw.deleteAll()
    draw.changeMode('simple_select')
    setCursor('') // 恢复默认鼠标指针
    isDrawing.value = false
  }
}
//矩形模式
const modes = MapboxDraw.modes
modes.draw_rectangle = DrawRectangle.default
//监听画笔事件
const handleDraw = (e: any) => {
  let type = drawType.value
  let position1 = e.features[0].geometry.coordinates
  //画笔化矩形
  if (drawType.value == 'draw_polygon' || drawType.value == 'draw_rectangle') {
    //
    let polygon = turf.polygon(position1)
    let value = turf.area(polygon)
    // console.log("区域面积",area);
    //计算质心坐标
    let centroid = turf.centroid(polygon)
    let { coordinates } = centroid.geometry
    let position = { lng: coordinates[0], lat: coordinates[1] }
    mapboxPopup({ map, position, value, type })
    //处理高亮图层数据
    handleHeightLayer(e)
  } else if (drawType.value == 'draw_line_string') {
    // console.log(position1);
    let point1 = turf.point(position1[0])
    let point2 = turf.point(position1[position1.length - 1])
    //计算线的中心点要素
    let midpoint = turf.midpoint(point1, point2)
    //计算中心点坐标
    let { coordinates } = midpoint.geometry
    let line = turf.lineString(position1)
    //计算线的长度
    let value = turf.length(line)
    // console.log("object",length);
    let position = { lng: coordinates[0], lat: coordinates[1] }

    mapboxPopup({ map, position, value, type })
  }
}
// //配置draw绘制参数
// draw = new MapboxDraw({
//   //默认控件显示方式。如果设置为true，则会添加所有的绘图控件
//   displayControlsDefault: false,
// })
//设置鼠标指针样式
const setCursor = (cursorStyle: any) => {
  if (map) {
    map.getCanvas().style.cursor = cursorStyle
  }
}
//自定义画笔模式
const activeDraw = () => {
  if (!draw) return
  let drawMode = drawType.value
  //画笔模式 draw_point draw_polygon draw_line_string
  draw.changeMode(drawMode)
  setCursor('crosshair') // 设置鼠标指针为十字
  isDrawing.value = true
}
//监听画笔模式
const handleModeChange = (e: any) => {
  // 如果切换到非绘图模式，恢复鼠标指针
  if (e.mode === 'simple_select' || e.mode === 'direct_select') {
    setCursor('')
    isDrawing.value = false
  }
}
onMounted(async () => {
  map = useMapStore().map
  // 确保地图已加载完成
  await map.once('style.load')
  await getData() // 等待数据加载完成
  initDraw() //初始化画笔
  //渲染图层
  renderLayer()
})
// 初始化 draw 控件
const initDraw = () => {
  // 配置 draw 绘制参数
  draw = new (window as any).MapboxDraw({
    displayControlsDefault: false,
    modes: modes, // 添加自定义模式
  })
  // 将 draw 控件添加到地图
  map.addControl(draw)
  // 添加事件监听
  map.on('draw.create', handleDraw)
  map.on('draw.modechange', handleModeChange)
}
onUnmounted(() => {
  // 清理资源
  if (map) {
    map.off('draw.create', handleDraw)
    map.off('draw.modechange', handleModeChange)
    if (draw) {
      map.removeControl(draw)
    }
  }
})
</script>

<style lang="scss" scoped>
.mapTool {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  position: fixed;
  top: 60px;
  left: 50px;
  /* width: 100px; */
  /* height: 30px; */
  z-index: 1;
}
</style>
